const { dialog } = require('@electron/remote');
const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');

document.addEventListener('DOMContentLoaded', () => {
    // 初始化视图切换功能
    let isListView = localStorage.getItem('photoViewMode') === 'list';
    const viewToggleBtn = document.getElementById('viewToggleBtn');
    const photoGrid = document.getElementById('photoGrid');

    function updateViewToggleButton() {
        const viewIcon = viewToggleBtn.querySelector('.view-icon');
        const viewText = viewToggleBtn.querySelector('.view-text');
        if (isListView) {
            viewIcon.textContent = '📱';
            viewText.textContent = '网格视图';
            photoGrid.classList.add('list-view');
        } else {
            viewIcon.textContent = '📋';
            viewText.textContent = '列表视图';
            photoGrid.classList.remove('list-view');
        }
    }

    viewToggleBtn.addEventListener('click', () => {
        isListView = !isListView;
        localStorage.setItem('photoViewMode', isListView ? 'list' : 'grid');
        updateViewToggleButton();
    });

    // 初始化视图模式
    updateViewToggleButton();
});

// 数据库连接配置
const dbConfig = {
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'photo_album'
};

// 初始化数据库连接
async function initDatabase() {
    const connection = await mysql.createConnection(dbConfig);
    
    // 创建photos表
    await connection.execute(`
        CREATE TABLE IF NOT EXISTS photos (
            id INT AUTO_INCREMENT PRIMARY KEY,
            filename VARCHAR(255) NOT NULL,
            category VARCHAR(50) NOT NULL,
            filepath TEXT NOT NULL,
            user_id INT NOT NULL,
            upload_date DATETIME DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id)
        )
    `);

    // 创建或更新users表
    await connection.execute(`
        CREATE TABLE IF NOT EXISTS users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            username VARCHAR(50) NOT NULL UNIQUE,
            password VARCHAR(255) NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
    `);

    // 创建photo_groups表
    await connection.execute(`
        CREATE TABLE IF NOT EXISTS photo_groups (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(50) NOT NULL,
            created_by INT NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (created_by) REFERENCES users(id)
        )
    `);

    // 创建group_members表
    await connection.execute(`
        CREATE TABLE IF NOT EXISTS group_members (
            id INT AUTO_INCREMENT PRIMARY KEY,
            group_id INT NOT NULL,
            user_id INT NOT NULL,
            joined_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (group_id) REFERENCES photo_groups(id),
            FOREIGN KEY (user_id) REFERENCES users(id),
            UNIQUE KEY unique_group_member (group_id, user_id)
        )
    `);

    return connection;
}

// 上传照片
async function uploadPhoto() {
    try {
        const result = await dialog.showOpenDialog({
            properties: ['openFile', 'multiSelections'],
            filters: [{ name: 'Images', extensions: ['jpg', 'png', 'gif'] }]
        });

        if (!result.canceled) {
            const category = await showCategoryDialog();
            if (!category) return;

            const connection = await initDatabase();
            const uploadDir = path.join(__dirname, 'uploads');
            
            // 创建上传目录
            if (!fs.existsSync(uploadDir)) {
                fs.mkdirSync(uploadDir);
            }

            for (const filePath of result.filePaths) {
                const originalFilename = path.basename(filePath);
                const fileExt = path.extname(originalFilename);
                const fileNameWithoutExt = path.basename(originalFilename, fileExt);
                const timestamp = Date.now();
                const uniqueFilename = `${fileNameWithoutExt}_${timestamp}${fileExt}`;
                const destPath = path.join(uploadDir, uniqueFilename);
                
                // 复制文件到uploads目录
                fs.copyFileSync(filePath, destPath);

                // 保存到数据库
                const currentUser = JSON.parse(localStorage.getItem('currentUser'));
                await connection.execute(
                    'INSERT INTO photos (filename, category, filepath, user_id) VALUES (?, ?, ?, ?)',
                    [originalFilename, category, destPath, currentUser.id]
                );
            }

            await loadPhotos(category);
            connection.end();
        }
    } catch (error) {
        console.error('上传失败:', error);
        alert('上传失败: ' + error.message);
    }
}

// 显示分类选择对话框
async function showCategoryDialog() {
    const categories = ['全部照片', '家庭相册', '旅行照片', '其他'];
    const categoryList = categories.map(cat => `<div class="category-item" data-category="${cat}">${cat}</div>`).join('');

    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-content">
            <h3>选择相册分类</h3>
            <div class="category-grid">${categoryList}</div>
            <button class="cancel-btn" onclick="this.parentElement.parentElement.remove()">取消</button>
        </div>
    `;

    document.body.appendChild(modal);

    return new Promise(resolve => {
        const categoryItems = modal.querySelectorAll('.category-item');
        categoryItems.forEach(item => {
            item.addEventListener('click', () => {
                const category = item.dataset.category;
                modal.remove();
                resolve(category);
            });
        });

        modal.querySelector('.cancel-btn').addEventListener('click', () => {
            resolve(null);
        });
    });
}

// 加载照片
async function loadPhotos(category = '全部照片', searchQuery = '', sortOption = 'date-desc') {
    try {
        const connection = await initDatabase();
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));
        const isListView = localStorage.getItem('photoViewMode') === 'list';
        const photoGrid = document.getElementById('photoGrid');
        
        if (isListView) {
            photoGrid.classList.add('list-view');
        } else {
            photoGrid.classList.remove('list-view');
        }

        // 获取用户所在的所有分组
        const [groups] = await connection.execute(
            'SELECT group_id FROM group_members WHERE user_id = ?',
            [currentUser.id]
        );

        let query = 'SELECT DISTINCT p.*, u.username as uploader_name FROM photos p';
        let params = [];

        if (groups.length > 0) {
            const groupIds = groups.map(g => g.group_id);
            query += ' LEFT JOIN group_members gm ON gm.group_id IN (' + groupIds.join(',') + ')';
            query += ' LEFT JOIN users u ON p.user_id = u.id';
            query += ' WHERE (p.user_id = ? OR gm.user_id = p.user_id)';
        } else {
            query += ' LEFT JOIN users u ON p.user_id = u.id';
            query += ' WHERE p.user_id = ?';
        }
        params.push(currentUser.id);

        if (category !== '全部照片') {
            query += ' AND p.category = ?';
            params.push(category);
        }

        if (searchQuery) {
            query += ' AND p.filename LIKE ?';
            params.push(`%${searchQuery}%`);
        }

        switch (sortOption) {
            case 'date-asc':
                query += ' ORDER BY p.upload_date ASC';
                break;
            case 'name-asc':
                query += ' ORDER BY p.filename ASC';
                break;
            case 'name-desc':
                query += ' ORDER BY p.filename DESC';
                break;
            default:
                query += ' ORDER BY p.upload_date DESC';
        }

        const [rows] = await connection.execute(query, params);
        photoGrid.innerHTML = '';

        if (rows.length === 0) {
            const noPhotosMessage = document.createElement('div');
            noPhotosMessage.className = 'no-photos-message';
            noPhotosMessage.textContent = '暂无照片';
            photoGrid.appendChild(noPhotosMessage);
        } else {
            rows.forEach(photo => {
                const container = document.createElement('div');
                container.className = 'photo-item-container';

                const img = document.createElement('img');
                img.src = `file://${photo.filepath}`;
                img.className = 'photo-item';
                img.title = photo.filename;
                img.onclick = () => showPhotoDetails(photo);

                const name = document.createElement('div');
                name.className = 'photo-name';
                name.textContent = photo.filename;

                const uploader = document.createElement('div');
                uploader.className = 'photo-uploader';
                uploader.textContent = `上传者: ${photo.uploader_name}`;

                const actions = document.createElement('div');
                actions.className = 'photo-actions';
                actions.innerHTML = photo.user_id === currentUser.id ? `
                    <button class="action-btn" onclick="showRenameModal(${photo.id})">重命名</button>
                    <button class="action-btn" onclick="deletePhoto(${photo.id})">删除</button>
                ` : '';

                container.appendChild(img);
                container.appendChild(name);
                container.appendChild(uploader);
                container.appendChild(actions);
                photoGrid.appendChild(container);
            });
        }

        connection.end();
    } catch (error) {
        console.error('加载照片失败:', error);
        alert('加载照片失败: ' + error.message);
    }
}

// 搜索和排序事件监听
document.getElementById('photoSearch').addEventListener('input', (e) => {
    const searchQuery = e.target.value;
    const sortOption = document.getElementById('photoSort').value;
    const currentCategory = document.querySelector('.category-list li.active')?.textContent || '全部照片';
    loadPhotos(currentCategory, searchQuery, sortOption);
});

document.getElementById('photoSort').addEventListener('change', (e) => {
    const sortOption = e.target.value;
    const searchQuery = document.getElementById('photoSearch').value;
    const currentCategory = document.querySelector('.category-list li.active')?.textContent || '全部照片';
    loadPhotos(currentCategory, searchQuery, sortOption);
});

// 重命名照片
let currentPhotoId = null;

function showRenameModal(photoId) {
    currentPhotoId = photoId;
    document.getElementById('renameModal').style.display = 'block';
    document.getElementById('newPhotoName').value = '';
}

function closeRenameModal() {
    document.getElementById('renameModal').style.display = 'none';
    currentPhotoId = null;
}

async function confirmRename() {
    const newName = document.getElementById('newPhotoName').value;
    if (!newName) {
        alert('请输入新的文件名');
        return;
    }
    
    await renamePhoto(currentPhotoId, newName);
    closeRenameModal();
}

async function renamePhoto(photoId, newName) {

    try {
        const connection = await initDatabase();
        const [rows] = await connection.execute('SELECT * FROM photos WHERE id = ?', [photoId]);
        if (rows.length === 0) {
            alert('照片不存在');
            connection.end();
            return;
        }

        const photo = rows[0];
        const oldPath = photo.filepath;
        const fileExt = path.extname(photo.filename);
        const newNameWithExt = newName.endsWith(fileExt) ? newName : newName + fileExt;
        const newPath = path.join(path.dirname(oldPath), newNameWithExt);

        // 检查文件是否存在
        if (!fs.existsSync(oldPath)) {
            alert('原文件不存在');
            connection.end();
            return;
        }

        // 检查新文件名是否已存在
        if (fs.existsSync(newPath)) {
            alert('该文件名已存在，请使用其他名称');
            connection.end();
            return;
        }

        // 重命名文件
        try {
            fs.renameSync(oldPath, newPath);
        } catch (error) {
            console.error('文件重命名失败:', error);
            alert('文件重命名失败: ' + error.message);
            connection.end();
            return;
        }

        // 更新数据库
        await connection.execute(
            'UPDATE photos SET filename = ?, filepath = ? WHERE id = ?',
            [newNameWithExt, newPath, photoId]
        );

        connection.end();
        await loadPhotos(); // 重新加载照片列表
        alert('重命名成功');
    } catch (error) {
        console.error('重命名失败:', error);
        alert('重命名失败: ' + error.message);
    }
}

// 下载照片
async function downloadPhoto() {
    try {
        const currentPhotoPath = document.querySelector('#photoModal img').src;
        const filePath = currentPhotoPath.replace('file://', '');
        const fileName = path.basename(filePath);

        const result = await dialog.showSaveDialog({
            defaultPath: fileName,
            filters: [{ name: 'Images', extensions: ['jpg', 'png', 'gif'] }]
        });

        if (!result.canceled) {
            fs.copyFileSync(filePath, result.filePath);
            alert('下载成功');
        }
    } catch (error) {
        console.error('下载失败:', error);
        alert('下载失败: ' + error.message);
    }
}
//删除照片
async function deletePhoto(photoId) {
    if (!confirm('确定要删除这张照片吗？')) return;

    try {
        const connection = await initDatabase();
        const [rows] = await connection.execute('SELECT filepath FROM photos WHERE id = ?', [photoId]);
        if (rows.length > 0) {
            fs.unlinkSync(rows[0].filepath);
            await connection.execute('DELETE FROM photos WHERE id = ?', [photoId]);
        }
        connection.end();
        loadPhotos();
    } catch (error) {
        console.error('删除失败:', error);
        alert('删除失败: ' + error.message);
    }
}

// 显示照片详情
function showPhotoDetails(photo) {
    const modal = document.getElementById('photoModal');
    const modalImage = document.getElementById('modalImage');
    const photoDetails = document.getElementById('photoDetails');

    modalImage.src = `file://${photo.filepath}`;
    const stats = fs.statSync(photo.filepath);
    const fileSize = (stats.size / 1024 / 1024).toFixed(2);
    const uploadDate = new Date(photo.upload_date).toLocaleString();

    photoDetails.innerHTML = `
        <p>文件名：${photo.filename}</p>
        <p>分类：${photo.category}</p>
        <p>大小：${fileSize} MB</p>
        <p>上传时间：${uploadDate}</p>
    `;

    modal.style.display = 'flex';
    
    // 添加点击空白处关闭功能
    modal.onclick = function(event) {
        if (event.target === modal) {
            closePhotoModal();
        }
    };
}

// 关闭照片详情
function closePhotoModal() {
    const modal = document.getElementById('photoModal');
    modal.style.display = 'none';
}

// 分类点击事件更新
document.getElementById('categoryList').addEventListener('click', (e) => {
    if (e.target.tagName === 'LI') {
        const categoryItems = document.querySelectorAll('.category-list li');
        categoryItems.forEach(item => item.classList.remove('active'));
        e.target.classList.add('active');

        const category = e.target.textContent;
        const searchQuery = document.getElementById('photoSearch').value;
        const sortOption = document.getElementById('photoSort').value;
        loadPhotos(category, searchQuery, sortOption);
    }
});

// 初始加载
loadPhotos();

// 分类点击事件
document.getElementById('categoryList').addEventListener('click', (e) => {
    if (e.target.tagName === 'LI') {
        const category = e.target.textContent;
        loadPhotos(category);
    }
});

// 添加上传按钮点击事件
document.getElementById('uploadBtn').addEventListener('click', uploadPhoto);

// 初始加载
loadPhotos();

// 分类点击事件
document.getElementById('categoryList').addEventListener('click', (e) => {
    if (e.target.tagName === 'LI') {
        const category = e.target.textContent;
        loadPhotos(category);
    }
});

// 初始加载
loadPhotos();

// 创建分组
async function createGroup() {
    console.log('创建分组按钮被点击');
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-content">
            <h3>创建新分组</h3>
            <input type="text" id="groupNameInput" placeholder="请输入分组名称" class="group-input">
            <div class="button-group">
                <button class="confirm-btn">确认</button>
                <button class="cancel-btn">取消</button>
            </div>
        </div>
    `;

    document.body.appendChild(modal);

    return new Promise((resolve) => {
        const confirmBtn = modal.querySelector('.confirm-btn');
        const cancelBtn = modal.querySelector('.cancel-btn');
        const input = modal.querySelector('#groupNameInput');

        confirmBtn.addEventListener('click', async () => {
            const groupName = input.value.trim();
            console.log('输入的分组名称:', groupName);

            if (!groupName) {
                alert('请输入分组名称');
                return;
            }

            try {
                console.log('开始创建分组...');
                const connection = await initDatabase();
                const currentUser = JSON.parse(localStorage.getItem('currentUser'));

                // 创建分组
                const [result] = await connection.execute(
                    'INSERT INTO photo_groups (name, created_by) VALUES (?, ?)',
                    [groupName, currentUser.id]
                );

                // 将创建者添加到分组成员中
                await connection.execute(
                    'INSERT INTO group_members (group_id, user_id) VALUES (?, ?)',
                    [result.insertId, currentUser.id]
                );

                connection.end();
                console.log('分组创建成功');
                alert('分组创建成功');
                modal.remove();
                showGroups();
            } catch (error) {
                console.error('创建分组失败:', error);
                alert('创建分组失败: ' + error.message);
            }
        });

        cancelBtn.addEventListener('click', () => {
            console.log('取消创建分组');
            modal.remove();
            resolve(null);
        });
    });
}

// 邀请用户加入分组
async function inviteToGroup(groupId) {
    try {
        const connection = await initDatabase();
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));

        // 验证是否是分组创建者
        const [groups] = await connection.execute(
            'SELECT * FROM photo_groups WHERE id = ? AND created_by = ?',
            [groupId, currentUser.id]
        );

        if (groups.length === 0) {
            alert('您没有权限邀请成员加入此分组');
            connection.end();
            return;
        }

        // 创建模态框
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.style.display = 'block';
        modal.innerHTML = `
            <div class="modal-content">
                <h3>邀请用户</h3>
                <input type="text" id="inviteUsername" placeholder="请输入用户名" class="invite-input">
                <div class="button-group">
                    <button class="confirm-btn" onclick="confirmInvite(${groupId})">确认</button>
                    <button class="cancel-btn" onclick="this.parentElement.parentElement.parentElement.remove()">取消</button>
                </div>
            </div>
        `;

        document.body.appendChild(modal);

        // 绑定按钮事件
        const confirmBtn = modal.querySelector('.confirm-btn');
        const cancelBtn = modal.querySelector('.cancel-btn');
        const input = modal.querySelector('#inviteUsernameInput');

        confirmBtn.addEventListener('click', async () => {
            const inviteUsername = input.value.trim();
            if (!inviteUsername) {
                alert('请输入用户名');
                return;
            }

            // 查找用户
            const [users] = await connection.execute(
                'SELECT * FROM users WHERE username = ?',
                [inviteUsername]
            );

            if (users.length === 0) {
                alert('用户不存在');
                return;
            }

            const invitedUser = users[0];

            // 检查用户是否已经在分组中
            const [members] = await connection.execute(
                'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
                [groupId, invitedUser.id]
            );

            if (members.length > 0) {
                alert('该用户已经在分组中');
                return;
            }

            // 添加用户到分组
            await connection.execute(
                'INSERT INTO group_members (group_id, user_id) VALUES (?, ?)',
                [groupId, invitedUser.id]
            );

            alert('邀请成功，用户已加入分组');
            modal.remove();
            // 刷新分组列表
            showGroups();
        });

        cancelBtn.addEventListener('click', () => {
            modal.remove();
        });

        // 点击空白处关闭
        modal.onclick = function(event) {
            if (event.target === modal) {
                modal.remove();
            }
        };

    } catch (error) {
        console.error('邀请失败:', error);
        alert('邀请失败: ' + error.message);
    } finally {
        if (connection) {
            connection.end();
        }
    }
}

// 显示分组管理按钮
const groupManageBtn = document.createElement('button');
groupManageBtn.id = 'groupManageBtn';
groupManageBtn.className = 'action-btn';
groupManageBtn.textContent = '分组管理';
groupManageBtn.onclick = showGroups;

// 将分组管理按钮添加到工具栏
const toolbar = document.querySelector('.toolbar');
if (toolbar) {
    toolbar.appendChild(groupManageBtn);
}

// 添加分组管理按钮
const sidebar = document.querySelector('.sidebar');
const groupButtons = document.createElement('div');
groupButtons.className = 'group-buttons';
groupButtons.innerHTML = `
    <button class="group-btn create-group-btn">创建分组</button>
`;
sidebar.insertBefore(groupButtons, sidebar.querySelector('h3'));

// 添加事件监听器
document.querySelector('.create-group-btn').addEventListener('click', createGroup);

// 添加分组按钮样式
const style = document.createElement('style');
style.textContent = `
    .group-buttons {
        margin: 10px 0;
        display: flex;
        flex-direction: column;
        gap: 5px;
    }
    .group-btn {
        padding: 8px;
        background-color: #4CAF50;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }
    .group-btn:hover {
        background-color: #45a049;
    }
`;
document.head.appendChild(style);

document.getElementById('categoryList').addEventListener('click', (e) => {
    if (e.target.tagName === 'LI') {
        const category = e.target.textContent;
        loadPhotos(category);
    }
});

// 初始加载
loadPhotos();

// 显示分组列表
async function showGroups() {
    try {
        const connection = await initDatabase();
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));

        // 获取用户所在的所有分组
        const [groups] = await connection.execute(`
            SELECT g.*, 
                   (g.created_by = ?) as is_owner,
                   GROUP_CONCAT(u.username) as member_names
            FROM photo_groups g
            LEFT JOIN group_members gm ON g.id = gm.group_id
            LEFT JOIN users u ON gm.user_id = u.id
            WHERE g.id IN (
                SELECT group_id 
                FROM group_members 
                WHERE user_id = ?
            )
            GROUP BY g.id
        `, [currentUser.id, currentUser.id]);

        const groupList = document.getElementById('groupList');
        groupList.innerHTML = '';

        groups.forEach(group => {
            const groupItem = document.createElement('div');
            groupItem.className = 'group-item';

            const memberNames = group.member_names ? group.member_names.split(',').join(', ') : '';

            groupItem.innerHTML = `
                <h3>${group.name}</h3>
                <p>创建时间: ${new Date(group.created_at).toLocaleString()}</p>
                <p>成员: ${memberNames}</p>
            `;

            groupList.appendChild(groupItem);
        });

        connection.end();
    } catch (error) {
        console.error('加载分组失败:', error);
        alert('加载分组失败: ' + error.message);
    }
}

// 删除分组
async function deleteGroup(groupId) {
    if (!confirm('确定要删除这个分组吗？所有成员将被移除。')) return;

    try {
        const connection = await initDatabase();
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));

        // 验证是否是分组创建者
        const [groups] = await connection.execute(
            'SELECT * FROM photo_groups WHERE id = ? AND created_by = ?',
            [groupId, currentUser.id]
        );

        if (groups.length === 0) {
            alert('您没有权限删除此分组');
            connection.end();
            return;
        }

        // 删除分组成员
        await connection.execute('DELETE FROM group_members WHERE group_id = ?', [groupId]);
        // 删除分组
        await connection.execute('DELETE FROM photo_groups WHERE id = ?', [groupId]);

        connection.end();
        alert('分组删除成功');
        // 刷新分组列表
        showGroups();
    } catch (error) {
        console.error('删除分组失败:', error);
        alert('删除分组失败: ' + error.message);
    }
}

// 退出分组
async function leaveGroup(groupId) {
    if (!confirm('确定要退出这个分组吗？')) return;

    try {
        const connection = await initDatabase();
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));

        // 验证是否是分组成员
        const [members] = await connection.execute(
            'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
            [groupId, currentUser.id]
        );

        if (members.length === 0) {
            alert('您不是该分组成员');
            connection.end();
            return;
        }

        // 检查是否是分组创建者
        const [groups] = await connection.execute(
            'SELECT * FROM photo_groups WHERE id = ? AND created_by = ?',
            [groupId, currentUser.id]
        );

        if (groups.length > 0) {
            alert('分组创建者不能退出分组，请使用删除分组功能');
            connection.end();
            return;
        }

        // 退出分组
        await connection.execute(
            'DELETE FROM group_members WHERE group_id = ? AND user_id = ?',
            [groupId, currentUser.id]
        );

        connection.end();
        alert('已退出分组');
        // 刷新分组列表
        showGroups();
    } catch (error) {
        console.error('退出分组失败:', error);
        alert('退出分组失败: ' + error.message);
    }
}

document.getElementById('categoryList').addEventListener('click', (e) => {
    if (e.target.tagName === 'LI') {
        const category = e.target.textContent;
        loadPhotos(category);
    }
});

// 初始加载
loadPhotos();

// 检查用户是否已登录
checkAuth();

// 显示用户信息
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser) {
    document.getElementById('username').textContent = currentUser.username;
}

// 绑定分组按钮点击事件
const groupButton = document.querySelector('.group-btn');
if (groupButton) {
    groupButton.addEventListener('click', showGroups);
}

// 添加退出登录功能
function logout() {
    localStorage.removeItem('currentUser');
    window.location.href = 'login.html';
}

// 显示分组信息
async function showGroups() {
    try {
        const connection = await initDatabase();
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));

        // 获取用户创建的分组
        const [createdGroups] = await connection.execute(
            'SELECT pg.*, COUNT(gm.id) as member_count FROM photo_groups pg ' +
            'LEFT JOIN group_members gm ON pg.id = gm.group_id ' +
            'WHERE pg.created_by = ? ' +
            'GROUP BY pg.id',
            [currentUser.id]
        );

        // 获取用户加入的分组（不包括自己创建的）
        const [joinedGroups] = await connection.execute(
            'SELECT pg.*, u.username as creator_name, COUNT(gm2.id) as member_count ' +
            'FROM photo_groups pg ' +
            'JOIN group_members gm ON pg.id = gm.group_id ' +
            'JOIN users u ON pg.created_by = u.id ' +
            'LEFT JOIN group_members gm2 ON pg.id = gm2.group_id ' +
            'WHERE gm.user_id = ? AND pg.created_by != ? ' +
            'GROUP BY pg.id',
            [currentUser.id, currentUser.id]
        );

        // 创建模态框
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.style.display = 'block';

        // 构建分组列表HTML
        let groupsHtml = '<div class="modal-content groups-modal">';
        groupsHtml += '<h3>我的分组</h3>';
        
        // 添加创建分组按钮
        groupsHtml += '<button class="create-group-btn" onclick="createGroup()">创建新分组</button>';

        // 显示创建的分组
        if (createdGroups.length > 0) {
            groupsHtml += '<h4>我创建的分组</h4>';
            groupsHtml += '<div class="group-list">';
            createdGroups.forEach(group => {
                groupsHtml += `
                    <div class="group-item">
                        <div class="group-info">
                            <span class="group-name">分组名: ${group.name}</span>
                            <span class="member-count">成员数：${group.member_count}</span>
                        </div>
                        <div class="group-actions">
                            <button onclick="deleteGroup(${group.id})">删除分组</button>
                            <button onclick="showGroupMembers(${group.id})">查看成员</button>
                        </div>
                    </div>
                `;
            });
            groupsHtml += '</div>';
        }

        // 显示加入的分组
        if (joinedGroups.length > 0) {
            groupsHtml += '<h4>我加入的分组</h4>';
            groupsHtml += '<div class="group-list">';
            joinedGroups.forEach(group => {
                groupsHtml += `
                    <div class="group-item">
                        <div class="group-info">
                            <span class="group-name">${group.name}</span>
                            <span class="creator-name">创建者：${group.creator_name}</span>
                            <span class="member-count">成员数：${group.member_count}</span>
                        </div>
                        <div class="group-actions">
                            <button onclick="leaveGroup(${group.id})">退出分组</button>
                            <button onclick="showGroupMembers(${group.id})">查看成员</button>
                        </div>
                    </div>
                `;
            });
            groupsHtml += '</div>';
        }

        if (createdGroups.length === 0 && joinedGroups.length === 0) {
            groupsHtml += '<p class="no-groups">暂无分组</p>';
        }

        groupsHtml += '<button class="close-btn" onclick="this.parentElement.parentElement.remove()">关闭</button>';
        groupsHtml += '</div>';

        modal.innerHTML = groupsHtml;
        document.body.appendChild(modal);

        // 添加点击空白处关闭功能
        modal.onclick = function(event) {
            if (event.target === modal) {
                modal.remove();
            }
        };

        connection.end();
    } catch (error) {
        console.error('加载分组信息失败:', error);
        alert('加载分组信息失败: ' + error.message);
    }
}

// 显示分组成员
// 邀请用户加入分组
async function inviteToGroup(groupId) {
    try {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.style.display = 'block';
        modal.innerHTML = `
            <div class="modal-content">
                <h3>邀请用户</h3>
                <input type="text" id="inviteUsername" placeholder="请输入用户名" class="invite-input">
                <div class="button-group">
                    <button class="confirm-btn" onclick="confirmInvite(${groupId})">确认</button>
                    <button class="cancel-btn" onclick="this.parentElement.parentElement.parentElement.remove()">取消</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
    } catch (error) {
        console.error('邀请用户失败:', error);
        alert('邀请用户失败: ' + error.message);
    }
}

// 确认邀请用户
async function confirmInvite(groupId) {
    const username = document.getElementById('inviteUsername').value.trim();
    if (!username) {
        alert('请输入用户名');
        return;
    }

    try {
        const connection = await initDatabase();
        
        // 检查用户是否存在
        const [users] = await connection.execute('SELECT id FROM users WHERE username = ?', [username]);
        if (users.length === 0) {
            alert('用户不存在');
            connection.end();
            return;
        }

        // 检查用户是否已经在分组中
        const [members] = await connection.execute(
            'SELECT * FROM group_members WHERE group_id = ? AND user_id = ?',
            [groupId, users[0].id]
        );

        if (members.length > 0) {
            alert('该用户已经在分组中');
            connection.end();
            return;
        }

        // 添加用户到分组
        await connection.execute(
            'INSERT INTO group_members (group_id, user_id) VALUES (?, ?)',
            [groupId, users[0].id]
        );

        connection.end();
        alert('邀请成功');
        document.querySelector('.modal').remove();
        showGroupMembers(groupId);
    } catch (error) {
        console.error('邀请用户失败:', error);
        alert('邀请用户失败: ' + error.message);
    }
}

async function showGroupMembers(groupId) {
    try {
        const connection = await initDatabase();
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));

        // 检查当前用户是否是分组创建者
        const [groups] = await connection.execute(
            'SELECT * FROM photo_groups WHERE id = ? AND created_by = ?',
            [groupId, currentUser.id]
        );
        const isCreator = groups.length > 0;

        const [members] = await connection.execute(
            'SELECT u.username, gm.joined_at FROM group_members gm ' +
            'JOIN users u ON gm.user_id = u.id ' +
            'WHERE gm.group_id = ?',
            [groupId]
        );

        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.style.display = 'block';

        let membersHtml = '<div class="modal-content members-modal">';
        membersHtml += '<h3>分组成员</h3>';
        membersHtml += '<div class="members-list">';

        members.forEach(member => {
            const joinDate = new Date(member.joined_at).toLocaleString();
            membersHtml += `
                <div class="member-item">
                    <span class="member-name">${member.username}</span>
                    <span class="join-date">加入时间：${joinDate}</span>
                </div>
            `;
        });

        membersHtml += '</div>';

        // 添加按钮容器
        membersHtml += '<div class="button-container" style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 15px;">';
        // 如果是创建者，显示邀请用户按钮
        if (isCreator) {
            membersHtml += `<button class="invite-btn" onclick="inviteToGroup(${groupId})">邀请用户</button>`;
        }
        membersHtml += '<button class="close-btn" onclick="this.parentElement.parentElement.parentElement.remove()">关闭</button>';
        membersHtml += '</div>';
        membersHtml += '</div>';

        modal.innerHTML = membersHtml;
        document.body.appendChild(modal);

        // 添加点击空白处关闭功能
        modal.onclick = function(event) {
            if (event.target === modal) {
                modal.remove();
            }
        };

        connection.end();
    } catch (error) {
        console.error('加载成员信息失败:', error);
        alert('加载成员信息失败: ' + error.message);
    }
}

// 显示用户信息模态框
async function showUserInfoModal() {
    try {
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (!currentUser || !currentUser.id) {
            alert('请先登录');
            return;
        }

        const connection = await initDatabase();

        // 获取用户信息和所属分组
        const [rows] = await connection.execute(
            'SELECT u.*, COUNT(DISTINCT gm.group_id) as group_count FROM users u ' +
            'LEFT JOIN group_members gm ON u.id = gm.user_id ' +
            'WHERE u.id = ? ' +
            'GROUP BY u.id',
            [currentUser.id]
        );

        const userInfo = rows[0];
        if (!userInfo) {
            alert('未找到用户信息');
            return;
        }

        // 获取用户创建的分组数量
        const [createdGroupsResult] = await connection.execute(
            'SELECT COUNT(*) as created_count FROM photo_groups WHERE created_by = ?',
            [currentUser.id]
        );

        const userInfoDetails = document.getElementById('userInfoDetails');
        userInfoDetails.innerHTML = `
            <p><strong>用户ID:</strong> ${userInfo.id}</p>
            <p><strong>用户名:</strong> ${userInfo.username}</p>
            <p><strong>注册时间:</strong> ${new Date(userInfo.created_at).toLocaleString('zh-CN')}</p>
            <p><strong>加入的分组数:</strong> ${userInfo.group_count || 0}</p>
            <p><strong>创建的分组数:</strong> ${createdGroupsResult[0].created_count || 0}</p>
        `;

        document.getElementById('userInfoModal').style.display = 'block';
        await connection.end();
    } catch (error) {
        console.error('获取用户信息失败:', error);
        alert('获取用户信息失败: ' + error.message);
    }
}

// 关闭用户信息模态框
function closeUserInfoModal() {
    document.getElementById('userInfoModal').style.display = 'none';
}

// 修改密码功能
async function changePassword() {
    const oldPassword = document.getElementById('oldPassword').value;
    const newPassword = document.getElementById('newPassword').value;

    if (!oldPassword || !newPassword) {
        alert('请输入旧密码和新密码');
        return;
    }

    try {
        const connection = await initDatabase();
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));

        // 验证旧密码
        const [rows] = await connection.execute(
            'SELECT * FROM users WHERE id = ? AND password = ?',
            [currentUser.id, oldPassword]
        );

        if (rows.length === 0) {
            alert('旧密码错误');
            connection.end();
            return;
        }

        // 更新密码和更新时间
        await connection.execute(
            'UPDATE users SET password = ?, update_time = NOW() WHERE id = ?',
            [newPassword, currentUser.id]
        );

        connection.end();
        closeModal();
        alert('密码修改成功');
        // 修改密码成功后退出到登录界面
        localStorage.removeItem('currentUser');
        window.location.href = 'login.html';
    } catch (error) {
        console.error('修改密码失败:', error);
        alert('修改密码失败: ' + error.message);
    }
}

// 显示修改密码对话框
function showChangePasswordModal() {
    document.getElementById('changePasswordModal').style.display = 'block';
}

// 关闭对话框
function closeModal() {
    document.getElementById('changePasswordModal').style.display = 'none';
    document.getElementById('oldPassword').value = '';
    document.getElementById('newPassword').value = '';
}